package cn.iocoder.yudao.module.iot.gateway.protocol.custom.xiaoan.tcp.util;

import cn.iocoder.yudao.framework.common.util.spring.SpringUtils;
import cn.iocoder.yudao.module.iot.core.mq.message.IotDeviceMessage;
import cn.iocoder.yudao.module.iot.gateway.service.device.message.IotDeviceMessageService;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.net.NetSocket;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class RequestUtils {
    public static void sendResponse(NetSocket socket, String requestId, String method, Object responseData, String codecType) {
        try {
            IotDeviceMessage responseMessage = IotDeviceMessage.replyOf(requestId, method, responseData,
                    null, null);
            byte[] encodedData = SpringUtils.getBean(IotDeviceMessageService.class).encodeDeviceMessage(responseMessage, codecType);
            socket.write(Buffer.buffer(encodedData));
        } catch (Exception e) {
            log.error("[sendResponse][发送响应失败，requestId: {}]", requestId, e);
        }
    }

    public static void sendResponse(NetSocket socket, IotDeviceMessage message, String codecType) {
        try {
            IotDeviceMessage responseMessage = IotDeviceMessage.replyOf(message.getRequestId(), message.getMethod(), message.getData(),
                    null, null);
            byte[] encodedData = SpringUtils.getBean(IotDeviceMessageService.class).encodeDeviceMessage(responseMessage, codecType);
            socket.write(Buffer.buffer(encodedData));
        } catch (Exception e) {
            log.error("[sendResponse][发送响应失败，requestId: {}]", message.getRequestId(), e);
        }
    }
}
